#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include "protocol.h"
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "Usage:./client_tcp server_ip server_port" << std::endl;
        return 1;
    }
    std::string serve_ip = argv[1];
    int serve_port = std::stoi(argv[2]);
    // 1创建套接字
    int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cout << "socket error" << std::endl;
        return 2;
    }
    // 2初始化
    struct sockaddr_in serve_addr;
    bzero(&serve_addr, sizeof(serve_addr));
    serve_addr.sin_family = AF_INET;
    serve_addr.sin_port = htons(serve_port);
    serve_addr.sin_addr.s_addr = inet_addr(serve_ip.c_str());
    // 3:conncet
    int n = connect(sockfd, (struct sockaddr *)&serve_addr, sizeof(serve_addr));
    if (n < 0)
    {
        std::cout << "connect fail" << std::endl;
        return 3;
    }
    // 4 echo client
    std::string message;
    while (1)
    {
        int x, y;
        char oper;
        std::cout << "input x: ";
        std::cin >> x;
        std::cout << "input y: ";
        std::cin >> y;
        std::cout << "input oper: ";
        std::cin >> oper;

        Request req(x, y, oper);
        req.Serialize(message);
        Encode(message);

        n = send(sockfd, message.c_str(), message.size(), 0);
        if (n > 0)
        {
            char buffer[1024];
            int m = recv(sockfd, buffer, sizeof(buffer), 0);
            if (m > 0)
            {
                buffer[m] = 0;
                std::string package = buffer;
                std::string content;
                Decode(package, &content);

                Response res;
                res.Deserialize(content);

                std::cout << res.Result() << "[" << res.Code() << "]" << std::endl;
            }
            else
                break;
        }
        else
        {
            break;
        }
    }
    close(sockfd);
    return 0;
}